var playerData = require('../scripts/network/playerData');
var gameData = require('../scripts/network/gameData');
var engine = require('../scripts/network/MatchvsEngine');
var msg = require('../scripts/network/MatchvsMessage');
var response = require('../scripts/network/MatchvsResponse');
var mvs = require('../scripts/network/Matchvs');

cc.vv = {};
cc.vv.mainUIAction = require('../scripts/mainUiAction');

cc.bb = {};
cc.bb.log = require('../scripts/searchRoomLog');


var returnMsg = {                         //开房间返回的信息
    editBox: null,
    roomName: cc.String,
    canWatch: null,
}

var settingUI = {                          //设置UI
    _isVaild: false,
    _prefab: null,
    _toggle: null,
    _slider: null,
    _volumeLabel: null,
    _enterButton: null,
}

var helpUI = {
    _enterButton: null,
    _label: null,
    _prefab: null,
}

var audio;                                 //背景音乐
var audioVolume;
var audioToggle = true;

cc.Class ({
    extends: cc.Component,

    properties: {
        avatar: cc.Sprite,                 //头像精灵
        PName: cc.Label,                   //名字Label 不能使用 name 关键字
        PUserID: cc.Label,                 //用户ID Label
        kaifangjianButton: cc.Button,      //开房按钮
        kaifangjiemian: cc.Node,           //开房界面
        sousuofangjianButton: cc.Button,   //搜房按钮
        sousuofangjianjiemian: cc.Node,    //搜房界面
        suijipipeiButton: cc.Button,
        douziNum: cc.Label,

        roomMessageScrollView: {           //房间信息显示面板
            default: null,
            type: cc.ScrollView,
        },

        roomMeassageLabelLog: {             //信息显示条 ， 它放置在scrollBar下，和bar 同层，在开始的时候自身将不会显示
            default: null,
            type: cc.Node,
        },
        
        
        // labelLog: cc.Label,                  //暂未设置 ， 用于显示字符
        // LabelLogList: [],                    //在官方的联网实例中，先将信息 push 到数组中，用for 逐个控制输出
        // totalCount: 0,                       //用于计数数组长度
        // spacing: 0,                          //用于控制字符之间的宽度，两条信息的间隔

        backgroundAudio: {
            default: null,
            type: cc.AudioClip,
        },

        settingButton: cc.Button,
        gameHelp: cc.Button,
    },

    onLoad: function () {
        this.content = this.roomMessageScrollView.content;

        /*跳过MatchvsResponse 重载脚本直接进行回调绑定*/
        //mvs.response.createRoomResponse = this.createRoomResponse.bind(this);

        response.prototype.bind();          //回调绑定初始化
        response.prototype.mainInit(this);  //将本脚本的this 传递给 MatchvsResponse 脚本 
        //监听 开房回调事件
        this.node.on(msg.MATCHVS_CREATEROOMRESPONOSE,this.createRoomResponse,this);
        this.node.on(msg.MATCHVS_GETROOMLISTEXRESPONSE,this.getRoomListExResponse,this);
        //this.node.on();

        if (playerData.presentPlayer.isValid) {
            var player = playerData.presentPlayer;
        }else {
            //new cc.SpriteFrame() 用于查找网络图片
            //new cc.SpriteFrame(cc.url.raw()) 用于查找本地图片
            var player = playerData.player[Math.floor(Math.random()*10)];
        }
        
        //将随即得到角色信息保存在 playerData中，方便调用
        playerData.presentPlayer = player;
        console.log(playerData.presentPlayer);
        
        //this.avatar.spriteFrame = new cc.SpriteFrame(cc.url.raw(player.avatar));//使用这个会有报错，但不会有什么影响
        //使用loader.loadRes() 动态加载资源才是正确方式
        var selfAvatar = this.avatar;
        cc.loader.loadRes(player.avatar, cc.SpriteFrame, function (error, sp) {
            if(error){
                cc.error(error.message);
                return;
            }
            selfAvatar.spriteFrame = sp;
            //this.avatar.spriteFram = sp;
        });
        this.PName.string = player.name;                            //设置头像
        this.PUserID.string = gameData.userInfo.userID;             //设置ID

        playerData.presentPlayer.gameID = gameData.userInfo.userID; //将用于信息存储在playerData.presentPlayer中，便于使用
        playerData.presentPlayer.isValid = true;                    
        playerData.presentPlayer.name = player.name;
        playerData.presentPlayer.avatar = player.avatar;
        playerData.presentPlayer.sex = player.sex;
        playerData.presentPlayer.douziNum = player.huanledouNumber;
        this.douziNum.string = playerData.presentPlayer.douziNum;

        this.suijipipeiButton.node.on('click',this.joinRandomRoom,this);   //随机匹配按钮监听
        this.kaifangjianButton.node.on('click',this.createRoomUi,this);    //开房按钮监听
        cc.find("Canvas/createRoomUI/cancelButton").on('click',this.dismiss,this);  //开放界面取消按钮监听
        cc.find("Canvas/createRoomUI/enterButton").on('click', this.create,this);   //确定按钮监听
        cc.find("Canvas/createRoomUI/label/toggle").on('toggle', function (toggle) {
        //toggle开关监听   node.on('toggle',function(toggle){},this)
            if(toggle.isChecked){
                returnMsg.canWatch = 1;
            }else {
                returnMsg.canWatch = 2;
            }
            this.toggle = toggle;            //在其他函数调用this.toggle 就可以对toggle操作
            console.log(returnMsg.canWatch);
        },this);

        //这里使用returMsg.editBox 来存储 得到的editbox 控件，也是为了方便操作控件
        returnMsg.editBox = cc.find("Canvas/createRoomUI/editbox");
        //editbox监听事件 
        returnMsg.editBox.on('editing-did-ended', function(editbox) {
            //将输入的数据 赋值给 returnMsg.roomName
            returnMsg.roomName = editbox.string;
            //同时度gameData 也进行更新
            gameData.roomInfo.roomName = returnMsg.roomName;
            this.editbox = editbox;
            console.log(returnMsg.roomName);
        },this);

        //最终得到editBox的输入数据 用 'editing-return' 而不是 'editing-did-end'
        returnMsg.editBox.on('editing-return', function(editbox) {
            //将输入的数据 赋值给 returnMsg.roomName
            returnMsg.roomName = editbox.string;
            //同时度gameData 也进行更新
            gameData.roomInfo.roomName = returnMsg.roomName;
            this.editbox = editbox;
            console.log(returnMsg.roomName);
        },this);

        this.sousuofangjianButton.node.on('click',this.searchRoomUi,this);      //搜索房间按钮监听

        this.settingButton.node.on('click', function () {
            if(settingUI._isVaild) {

            }else {
                cc.vv.mainUIAction.xuanzeUIOut();
                this.setting();
            }
            
        },this);
        this.gameHelp.node.on('click', this.help, this);
        cc.find("Canvas/searchRoom/cancelButton").on('click',this.dismiss,this);
    },
    
    start () {
        audio = this.backgroundAudio;
        cc.audioEngine.playMusic(this.backgroundAudio,true);
        cc.audioEngine.setMusicVolume(0.5);
    },

    /**
     * 加入房间事件
     */
    joinRandomRoom: function () {
        var result = engine.prototype.joinRandomRoom();
        if( result == 0) {
            cc.director.loadScene('fight');
        }
        console.log(result);
    },

    createRoomUi: function () {
        cc.vv.mainUIAction.xuanzeUIOut(); //使用全局变量 cc.vv 来调用 mainUiAction 脚本
        this.kaifangjiemian.y = -47;      //这里并未使用prefab 来使用Ui， 而是直接放置在画布之外的地方
    },

    searchRoomUi: function () {
        cc.vv.mainUIAction.xuanzeUIOut();
        this.sousuofangjianjiemian.y = -47;
        var result = engine.prototype.getRoomListEx();
        console.log(result);
        
    },

    dismiss: function () {
        if(this.editbox){
            this.editbox.string ='';
        }
       
        cc.vv.mainUIAction.xuanzeUIIN();
        this.kaifangjiemian.y = -470;
        this.sousuofangjianjiemian.y = -470;
        this.content.removeAllChildren(true); //移除显示框的所有显示信息
    },

    create: function () {
        var result = engine.prototype.createRoom(returnMsg);
        // if(result == 0) {
        //     if(this.editbox){
        //         this.editbox.string ='';
        //     }
        //     if(this.toggle){
        //         this.toggle.isChecked = true;
        //     }
        //     this.kaifangjiemian.y = -470;
           
        // }
        console.log(result);
    },

    createRoomResponse: function (createRoomRsp) {
        playerData.gamePlayer.ownerID = createRoomRsp.owner;
        if(createRoomRsp.status == 200) {
            console.log("开房成功" + createRoomRsp.roomID);
            gameData.roomInfo.roomID = createRoomRsp.roomID;
            this.node.off(msg.MATCHVS_CREATEROOMRESPONOSE,this.createRoomResponse,this);
            this.node.off(msg.MATCHVS_GETROOMLISTEXRESPONSE,this.getRoomListExResponse,this);
            cc.director.loadScene('fight'); //这里必须在Response 中跳转， 不然在MatchvsResponse 中会出现 emit null or undefine 错误
        }else {
            console.log("开房失败" + createRoomRsp.status);
        }
    },

    getRoomListExResponse: function (rsp) {
        if(rsp.status == 200 ){
            console.log("搜索房间成功");
            console.log(rsp.roomAttrs);
            // for (var i=0; i<rsp.roomAttrs.length; i++) {
            //     console.log(rsp.roomAttrs[i].gamePlayer);
            //     this.searchRoomMessageLog(rsp.roomAttrs[i].roomName, rsp.roomAttrs[i].gamePlayer,
            //         rsp.roomAttrs[i].roomID);
                
            // }
            //this.searchRoomMessageLog(rsp.roomAttrs)
            

            //为什么 roomAttrs 再开多个房间的时候只有一个元素
            for (var i in rsp.roomAttrs) {
                var item = cc.instantiate(this.roomMeassageLabelLog);
                this.content.addChild(item);
                item.x = 0;
                item.getComponent('searchRoomLog').updataItem(rsp.roomAttrs[i].roomName, rsp.roomAttrs[i].gamePlayer,
                    rsp.roomAttrs[i].roomID);
            }
            
        }
    },

    searchRoomMessageLog: function (roomAttrs) {
        //在scrollView的content组建上添加 Layout  来实现自动排序，这样就不需要自己手动计算宽度，排序问题
        //首先对信息显示条实例化，添加到显示面板的content的组件上
        //最后通过全局变量(自定义) cc.bb 来调用面板的脚本 显示房间信息
        
        // var item = cc.instantiate(this.roomMeassageLabelLog);
        // this.content.addChild(item);
        // item.position = cc.v2(0,0);
        // cc.bb.log.updataItem(roomName, gamePlayer, roomID); 
    },

    setting: function () {
        cc.loader.loadRes('prefab/otherUI/setting', cc.Prefab, function(err, prefab) {
            if(err) {
                cc.error(err);
            }
            settingUI._prefab = cc.instantiate(prefab);
            cc.find('Canvas').addChild(settingUI._prefab);
            settingUI._prefab.position = cc.v2(0,0);
            settingUI._toggle = cc.find('Canvas/setting/toggle');
            settingUI._slider = cc.find('Canvas/setting/slider');
            settingUI._volumeLabel = cc.find('Canvas/setting/audioVolume').getComponent(cc.Label);
            settingUI._enterButton = cc.find('Canvas/setting/enter');
            if(audioVolume) {
                settingUI._volumeLabel.string = audioVolume;
                settingUI._slider.getComponent(cc.Slider).progress = audioVolume/10;
            }
            if(audioToggle) {

            }else {
                settingUI._toggle.getComponent(cc.Toggle).isChecked = false;
            }
            settingUI._toggle.on('toggle', function(toggle) {
                audioToggle = toggle.isChecked;
                if(toggle.isChecked) {
                    cc.audioEngine.playMusic(audio,true);
                }else {
                    cc.audioEngine.stopMusic(audio);
                }
            },this);

            settingUI._slider.on('slide', function(slide) {
                audioVolume = Math.round(slide.progress * 10);
                cc.audioEngine.setMusicVolume(audioVolume/10 *0.5);
                settingUI._volumeLabel.string = audioVolume;
            },this);

            settingUI._enterButton.on('click', function () {
                cc.find('Canvas').removeChild(settingUI._prefab);
                cc.vv.mainUIAction.xuanzeUIIN();
                settingUI._isVaild = false;
            },this);
            settingUI._isVaild = true;

        });
    },

    help: function () {
        cc.loader.loadRes('prefab/otherUI/helpLabel', cc.Prefab, function(err, prefab) {
            if(err) {
                cc.error(err);
            }
            helpUI._prefab = cc.instantiate(prefab);
            cc.find('Canvas/gameHelp').addChild(helpUI._prefab);
            helpUI._prefab.position = cc.v2(-100,-36);
            helpUI._enterButton = cc.find('Canvas/gameHelp/helpLabel/button');
            helpUI._label = cc.find('Canvas/gameHelp/helpLabel/msg');
            helpUI._enterButton.on('click', function () {
                var action = cc.spawn(cc.scaleTo(0.2,cc.v2(0.5,0.5)), cc.fadeOut(0.2));
                helpUI._prefab.runAction(action);
                cc.find('Canvas/gameHelp').removeChild(helpUI._prefab);
            },this);
        })
    }

});